﻿using MobiSms.DataModel;
using MobiSms.Library;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;

namespace MobiSms.ViewModel
{
    public class MessageCollectionViewModel : MainViewModel
    {
        public MessageCollectionViewModel()
        {
            if (!IsDesignMode)
            {
                LoadMessageOfMonth();
            }
        }

        private DateTime _selectedMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        public DateTime SelectedMonth
        {
            get { return _selectedMonth; }
            set
            {
                _selectedMonth = value;
                RaisePropertyChanged(() => SelectedMonth);
                if (!IsDesignMode)
                {
                    LoadMessageOfMonth();
                }
            }
        }

        private ObservableCollection<MessageInfo> _itemsOfMessage = new ObservableCollection<MessageInfo>();
        public ObservableCollection<MessageInfo> ItemsOfMessage
        {
            get { return _itemsOfMessage; }
            set
            {
                _itemsOfMessage = value;
                RaisePropertyChanged(() => ItemsOfMessage);
                RaisePropertyChanged(() => LoadPreviousCommand);
            }
        }

        public int ItemsCount
        {
            get
            {
                if (IsDesignMode)
                {
                    return 0;
                }
                return Database.CollectionOfMessages.Count();
            }
        }

        private void LoadMessageOfMonth()
        {
            IEnumerable<MessageInfo> items = Database.CollectionOfMessages.Where(m => m.SubmitTime > SelectedMonth && m.SubmitTime < SelectedMonth.AddMonths(1));

            ItemsOfMessage = new ObservableCollection<MessageInfo>(ItemsOfMessage.Concat(items).OrderByDescending(m => m.SubmitTime));

            if (items.Count() == 0 && ItemsOfMessage.Count < ItemsCount)
            {
                SelectedMonth = SelectedMonth.AddMonths(-1);
            }
        }

        public ICommand LoadPreviousCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return ItemsOfMessage == null || ItemsOfMessage.Count < ItemsCount; },
                    ExecuteCallback = delegate
                    {
                        SelectedMonth = SelectedMonth.AddMonths(-1);
                    }
                };
            }
        }
    }
}
